<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ include file="/WEB-INF/component/commonTagLib.jsp"%>

<!DOCTYPE html>
<html>
<head>
    <title><spring:message code="message.list.DingDanPeiSongMingXi"/></title>
    <%@ include file="/WEB-INF/component/commonCSS.jsp"%>
     <style type="text/css">
        div.group-info {
            margin-top: 10px !important;
            margin-bottom: 0px !important;
        }
        input.innerInput {
            width: 100%;
        }
        div.tablediv {
            width: 920px;
            margin: auto;
            margin-top: 20px;
            margin-bottom: 20px;
            border-top: 1px solid #cecece;
        }
        td.ui-sgcollapsed.sgexpanded>div, td.ui-sgcollapsed.sgcollapsed>div {
            width: 20px !important;
        }
        tr.ui-subgrid>td.subgrid-data {
            border-right: 1px solid #cecece;
            border-bottom: 1px solid #cecece;
        }
        div.tablediv div.ui-jqgrid-bdiv, div.tablediv div.ui-jqgrid-hdiv {
            border-right: 0px none;
            border-bottom: 0px none;
        }
        span.addRow {
            width: 20px;
            display: block;
            margin: auto;
            cursor: pointer;
        }
        td.subgrid-data {
            background-color: #FDF5E6;
        }
    </style>
</head>
<body class="skin-blue sidebar-mini fixed skin-blue-light-frame">
     
    <section class="content">
        <div class=" box box-primary">
            <div class="box-body">
                <div class="input">
		    		<div class="textalign1"><spring:message code="message.listForm.tongYongMing"/><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                        <input type="text" class="textinput" id="drugName" name="drugName" placeholder="<spring:message code="message.listForm.tongYongMing"/>/<spring:message code="message.listForm.pinYinMa"/>" />
                    </div>
                    <div hidden>
                        <div class="textalign1"><spring:message code="message.listForm.yaoPinBianMa"/><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                        <input type="text" class="textinput" id="drugCode" name="drugCode"  placeholder="<spring:message code="message.listForm.yaoPinBianMa"/>" />
                    </div>
                    </div>
                    <div class="textalign1"><spring:message code="message.listForm.ShengChanQiYe"/><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                         <input type="text" class="textinput" id="prodComp" name="prodComp"  placeholder="<spring:message code="message.listForm.ShengChanQiYe"/>/<spring:message code="message.listForm.pinYinMa"/>" />
                    </div>
					<div class="textalign1" >  
                   <button type="button" onclick="gridSerch();" class="btn btn-success btn-sm"  id="selectDicCompType"><spring:message code="message.button.seachSpacing"/></button>
                    </div>
                </div>
            </div>
        </div>
        
        <table class="jqgrid" id="gridlist"></table>
        <div id="gridpage"></div>
        
         <div class=" box box-warning bottongroup">
           	<button type="button" onclick="orderConfirmSelect(1);" class="btn btn-primary btn-sm"><spring:message code="message.button.QueRenShouHuo"/></button>
        	<button type="button" onclick="orderConfirmSelect(2);" class="btn btn-primary btn-sm"><spring:message code="message.listForm.WeiDaoHuo"/></button>
        </div>
        
   </section>
    
   <%@ include file="/WEB-INF/component/commonJS.jsp"%>
   <script type="text/javascript">
   var submitTyp = 0;   //  0未提交，1已提交
   
   //   增加批号行
   function addRow(subTableId) {
	   var rowId = $("#" + subTableId).getGridParam("records");
	   $("#" + subTableId).addRowData(rowId, {});
	   var $td = $("#" + subTableId).find(".confirmRemark0");
	   $td.attr("rowspan", rowId + 1);
	   var h = $td.height() - 2;
	   $td.children("textarea").css({
		   "height" : h + "px",
		   "min-height" : h + "px"
	   });
   }
   
   //   删除批号行
   function delRow(subTableId, rowId) {
	   var $td = $("#" + subTableId).find(".confirmRemark0");
	   $td.children("textarea").hide();
	   $("#" + subTableId).delRowData(rowId);
	   var rowId = $("#" + subTableId).getGridParam("records");
       $td.attr("rowspan", rowId);
       var h = $td.height() - 2;
       $td.children("textarea").css({
           "height" : h + "px",
           "min-height" : h + "px"
       });
       $td.children("textarea").show();
   }
   
   $(function () {
	   //绑定回车
	   $('#drugName,#drugCode,#prodComp').bind('keydown', function(event) {
	       if (event.keyCode == "13") {
	           $('#selectDicCompType').click();
	       }
	   });  
	 
	   $("#drugName").focus();//加载页面光标在第一个查询框内
	   
       $("#gridlist").jqGrid({
           url: "${ctx}/purOrderInfo/getConfirmRecpDetailDataList.html",
           mtype: "POST",
           postData:{"orderPackId":"${param.orderPackId}"},
           datatype: "json",
           autowidth: true,
           shrinkToFit: false,
           height: 315,
           colNames: [
                'orderCode',
                '状态',
				'<spring:message code="message.listForm.CaiGouJia"/>',
				'<spring:message code="message.listForm.CaiGouShuLiang"/>',
				'<spring:message code="message.listForm.CaiGouJinE"/>',
				'<spring:message code="message.listForm.yaoPinBianMa"/>',
				'<spring:message code="message.listForm.tongYongMing"/>', 
				'<spring:message code="message.listForm.jiXing"/>',
				'<spring:message code="message.listForm.guiGe"/>',
				'<spring:message code="message.listForm.zhuanHuanXiShu"/>',
				'<spring:message code="message.listForm.baoZhuangDanWei"/>', 
				'<spring:message code="message.listForm.caiZhi"/>',
				'<spring:message code="message.listForm.shengChanQiYe"/>',
				'国药准字',
				'<spring:message code="message.listForm.CaiGouXianJia"/>',
				'最高零售限价'
			],
			colModel: [
                { name: 'orderCode', width: 60, align: "right",sortable:false, hidden:true },
                { name: 'isRecepted',width: 60, align: "center",sortable:false},
				{ name: 'proPrice', width: 80, align: "right",sortable:false,
					formatter:function(cellvalue, options, row){
					    return formatAmount(cellvalue, options, row);
					}
				},
				{ name: 'proCount', width: 80, align: "center",sortable:false},
				{ name: 'buyPrice', width: 80, align: "right",sortable:false},
				{ name: 'drugCode', width: 100, hidden:true, align: "center",sortable:false,
					formatter:function(cellvalue, options, row){
					    // return drugInfoLink(cellvalue);
					    return cellvalue;
					}
				},
				{ name: 'drugName', width: 140, align: "left" ,sortable:false },
				{ name: 'formName', width: 80 , align: "center",sortable:false},
				{ name: 'specName', width: 80, align: "center" ,sortable:false},
				{ name: 'factor', width: 80, align: "center" ,sortable:false},
				{ name: 'unit', width: 60, align: "center" ,sortable:false},
				{ name: 'materialName', width: 60, hidden:true, align: "center" ,sortable:false},
				{ name: 'compName', width: 220, align: "left",sortable:false,
					formatter:function(cellvalue, options, row){
					    // return compInfoLink(row.prodCompcode, cellvalue, 1);
					    return cellvalue;
					}
				},
				{ name: 'drugMedicine', index: 'drugMedicine',width: 100, align: "center", sortable:false},
				{ name: 'proPriceLimit', width: 60,align:"right",sortable:false, hidden:true,
					formatter:function(cellvalue, options, row){
					    return formatAmount(cellvalue, options, row);
					}
				},
				{ name: 'retailPriceLimit', width: 60,align:"right",sortable:false, hidden:true,
					formatter:function(cellvalue, options, row){
					    return formatAmount(cellvalue, options, row);
					}
				}
			],
           rowNum: 20,
           rowList: [10, 20, 50, 100],
           rownumbers: true,
           pager: "#gridpage",
           multiselect: true, 
           viewrecords: true,
           gridComplete: function(){
               //序号列宽度自适应（参数为jqgridID）
           //    autoRNWidth("gridlist");
               //数据只有一条时默认选中（参数为jqgridID）
               selectByOneData("gridlist");
               
               $("td.ui-sgcollapsed.sgcollapsed:first").trigger("click");
           }, 
           caption: "<spring:message code="message.list.DingDanMingXiLieBiao"/>",
           jsonReader: {
               repeatitems: false,
               id: "orderCode"
           },
           subGrid: true,
           subGridOptions: {
        	   reloadOnExpand : false
           },
           subGridRowExpanded: function(subGridId, rowId) {
        	   $("tr.ui-subgrid>td:not(.subgrid-data)").remove();
        	   $("tr.ui-subgrid>td.subgrid-data").attr("colspan", 15);
        	   
        	   var subTableId = "subTable_" + rowId;
        	   $("#" + subGridId).append("<table id='" + subTableId + "' class='scroll'></table>");
        	   
        	   {
                   title= [
					   'delDetailId',
					   '状态',
					   '批号',
					   '有效期',
					   '配送数量',
					   '到货数量',
					   '备注'
				   ];
				   model= [
						{ name: 'delDetailId', index: 'ship', hidden:true, width: 80, align: "center", sortable:false},
						{ name: 'isRecepted', width: 80, align: "center",sortable:false},
						{ name: 'approveCode', width: 100, align: "center",sortable:false},
						{ name: 'credential', width: 140, align: "center",sortable:false},
						{ name: 'del_count', width: 80, align: "right",sortable:false},
						{ name: 'recpCount', width: 80, align: "right",sortable:false,
							formatter:function(cellvalue, options, row){
								if(cellvalue==null){
									return "";
								}else{
									return "<input class='gridText recpCount' type='text' style='text-align: right;' maxlength='11' value='"+cellvalue+"' />";
								}
						    }
						},
						{ name: 'remarks', width: 214, align: "center",sortable:false},
						
                   ];     
                   datatype = "json";
        	   }
                   $("#" + subTableId).jqGrid({
                	   url: "${ctx}/purOrderInfo/getConfirmRecpOrderDataList.html",
                       mtype: "POST",
                       postData:{"orderCode":rowId,"orderPackId":"${param.orderPackId}"},
                       datatype: "json",
                       autowidth: true,
                       shrinkToFit: true,
                       height: "auto",
                       colNames: title,
                       colModel: model,       
                       rownumbers: true,
                       beforeSelectRow: function(rowid, e) {
                           return false;    //  子表格无选中状态
                       }
                   });
        	   
        	   $("#" + subTableId).addRowData(0, {});
            }
       });
       $("#gridlist").jqGrid('navGrid', '#gridpage', { add: false, edit: false, del: false, search: false, refresh: false });
       $(window).trigger("resize");
       
       $("html").scrollTop(305);
   });
   
   function getFoucs(obj, rowId) {
       var text = $.trim($(obj).val());
       if (text != null && text != "") {
           var $checkbox = $("#jqg_gridlist_" + rowId);
           if ($checkbox.is(":not(:checked)")) {
               $("#gridlist").setSelection(rowId);
           }
       }
   }
   
   //查询
   function gridSerch() {
       var drugCode = $.trim($("#drugCode").val());
       var drugName = $.trim($("#drugName").val());
       var prodComp = $.trim($("#prodComp").val());
       $("#gridlist").jqGrid('setGridParam',{  
           datatype:'json',
           postData:{
               "drugCode":drugCode,
               "drugName":drugName,
               "compName":prodComp
           },
           page:1
       }).trigger("reloadGrid"); //重新载入  
   }
   
   // 确认收货
   function orderConfirmSelect(obj) {
	   if (submitTyp == 1) {
		   $.alert("后台处理中，请勿重复操作！", "warn");
           return;
	   }
	   
       var rowIds = $("#gridlist").jqGrid("getGridParam", "selarrrow") || [];
       if(rowIds.length <=0){
    	   $.HN.message.alert("请选择要操作的药品！", "<spring:message code="message.HN.alert.type"/>", "warn");
           return;
       }
       
       var approveCodeMap = {}; //  批号map(校验重复用)
       var invoiceNoMap = {};   //  发票号map(校验重复用)
       var list = [];    //  订单明细集合
       var array = [];//记录要勾选的ordercode
       var drugNames = '';
       //$("#gridlist").trigger("reloadGrid");
       //   循环获取子表格信息
       for (var i=0; i<rowIds.length; i++) {
           rowId = rowIds[i];
           var rowdata = $("#gridlist").jqGrid('getRowData', rowId);
           var orderCode = rowdata.orderCode || ""; //  订单明细编号
           var proPrice = rowdata.proPrice || "";   //  采购价
           var drugName = rowdata.drugName || "";   //  通用名
           var proCount = rowdata.proCount || 0;    //  采购数量
          
           var $subTable = $("#subTable_" + rowId); //  子表格
           var subRecords = $subTable.getGridParam("records") || 0; //  子表格记录数
           
           
           var recpCountSum = 0; //  同一商品不同批号的到货数量总和
           var dispatchInfoList = [];   //  某条明细多批号、发票等信息
           //   循环子表格的行
         
           if(subRecords == 0){
        	   array.push(rowId);
           }
           for (var j=0; j<subRecords; j++) {
        	   
        	   if(i<3){
                   drugNames+= rowdata.drugName+"<br/>"
                   if(i==2)
                   drugNames+='...';
                    	
               }
        	   //  获取表单对象
        	   var zRowData = $subTable.jqGrid('getRowData');
        	   
               var $recpCount = $subTable.find("input.recpCount:eq(" + j + ")");
               //   获取表单值
               var delDetailId = $.trim(zRowData[j].delDetailId);
               var approveCode = $.trim(zRowData[j].approveCode);
               var delCount = $.trim(zRowData[j].del_count);
               var recpCount = $.trim($recpCount.val());
        	   var invoiceDatetime = $.trim(zRowData[j].credential);
        	   var remarks = $.trim(zRowData[j].remarks);
        	   
        	   //  去除表单首尾空格
        	   $recpCount.val(recpCount);
       	   
        	   if(obj == 1){  
	        	   //  判断到货数量是否为空
	        	   if (recpCount == null || recpCount == "") {
	                   $.alert("请为采购价" + proPrice + "的" + drugName + "药品输入到货数量！", "warn");
	                   $delCount[0].focus();
	                   return;
	               }
	        	   
	        	   //  判断到货数量是否为正整数
	        	   if (isNaN(recpCount) || recpCount.indexOf(".") >= 0) {
	        		   $.alert("采购价" + proPrice + "的" + drugName + "药品到货数量为大于0的整数！", "warn");
	                   $delCount[0].focus();
	                   return;
	        	   } 
	        	   //  判断到货数量是否大于采购数量
	        	   if (Number(recpCount) > Number(delCount)) {
	                   $.alert("采购价" + proPrice + "的" + drugName + "药品到货数量不能大于配送数量！", "warn");
	                   $delCount[0].focus();
	                   return;
	               } else {
	            	   recpCountSum += Number(recpCount);
	               }
	        	   //  判断同一商品不同批号的到货数量总和是否大于采购数量
	               if (recpCountSum > Number(proCount)) {
	                   $.alert("采购价" + proPrice + "的" + drugName + "药品不同批号的到货数量总和不能大于采购数量！", "warn");
	                   $delCount[0].focus();
	                   return;
	               }
        	   }
        		   var dispatchInfo = {
                    	   "delDetailId":delDetailId,
                    	   "approveCode" : approveCode,
                    	   "recpCount" : recpCount,
                    	   "invoiceDatetime" : invoiceDatetime,
                    	   "remarks" : remarks
                       };
               dispatchInfoList.push(dispatchInfo);
           }
           var detail = {"orderCode": orderCode,"dispatchInfoList":dispatchInfoList };   //  一条明细信息
           list.push(detail);
       }
       console.log(json.jsonToString(list));
       for(var n=0;n<array.length;n++){
    	   $("#gridlist").setSelection(array[n], true);
       }
       
	   var tsName = '';
	   if(obj != 1){
			tsName = "未收货"
	   }else {
		  tsName = "收货"; 
	   }
       $.HN.message.confirm("确定以下药品"+tsName+"吗？<br/>"+drugNames, "<spring:message code="message.HN.alert.type"/>", "<spring:message code="message.lable.OKYES"/>").on(function(bool) {
           if (bool) {
        	   submitTyp = 1;
        	   var url = "${ctx}/purOrderInfo/confirmRecp.html";
        	   //已到货
        	   if(obj != 1){
        		   //未到货
            	   url = "${ctx}/purOrderInfo/notArrived.html";
        	   }
               $.post(url, {
            	   "orderPackId":"${param.orderPackId}",
            	   "orderDetails" : json.jsonToString(list)
               }, function(result) {
            	   submitTyp = 0;
                   if (result.success) {
                	   $.HN.message.alert("操作成功！", "", "success");
                       gridSerch();
                   } else {
                       $.HN.message.alert(result.msg, "", "error");
                   }
               }, "json").error(function(err) {
                   top.window.document.location = "${ctx}/login.html"; 
               }); 
           }
       });   
   }
        
   
   
   </script>
        
</body>
</html>
